﻿using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Entities;
using VitCode.Castle.Helper;

namespace AMS.Web
{
    public partial class Default : Page
    {
        public CastleAccess m_CastleAccess = new CastleAccess();

 
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        private void SetCookiesValue(string key,string val)
        {
            if(Response.Cookies!=null)
            {
                 Response.Cookies.Remove(key);
                 var cook = new HttpCookie(key, Server.UrlEncode(val)) { Expires = DateTime.Now.AddDays(1) };
                
                Response.Cookies.Add(cook);
            }
        }

 

        protected void Login_Click(object sender, EventArgs e)
        {
            //if(!CastleAccess.CheckDogKeys())
            //{
            //    Alert.MessageBox("读取加密狗失败!");
            //    return;
            //}
            string strCode = publ.GetCatchMsg(UserName.Value.Trim());
            string strPassword = publ.GetCatchMsg(Password.Value.Trim());
            strPassword = publ.VitEnctyptString(strPassword);

            User objCurUser = m_CastleAccess.CheckLogin(strCode, strPassword);
            if (objCurUser != null)
            {
                if (Response.Cookies != null)
                {
                    SetCookiesValue("LoginUserId", objCurUser.Id.ToString().Trim());
                    SetCookiesValue("Code", strCode);
                    SetCookiesValue("Password", strPassword);
                    SetCookiesValue("Name", objCurUser.Name);
                    if (objCurUser.UserGroup != null)
                        SetCookiesValue("UserGroupId", objCurUser.UserGroup.Id.ToString());
                    else
                        SetCookiesValue("UserGroupId", "00000000-0000-0000-0000-000000000000");
                    
                }
               if(m_CastleAccess.CheckIsAdmin(objCurUser.Id.ToString()))
               {
                   SetCookiesValue("Role", "admin");
               }
               else
               {
                   SetCookiesValue("Role", "no");
               }
              
                GenericContext.CurrUserCode = strCode;
                GenericContext.CurrUserId = objCurUser.Id;
                GenericContext.CurrUserName = objCurUser.Name;
                Guid id = GenericContext.CurrUserId;
                const string strURL = "MainWebForm/Main.aspx";
                Response.Redirect(strURL);

            }
            else
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "001", "<script>alert('密码错误!')</script>");
            }
        }
    }
}